import { Body, Controller, Get, HttpException, HttpStatus, Post, Request, Res, UseInterceptors, Query } from '@nestjs/common';
import { Response } from 'express';
import { VideoLibraryService } from './videoLibrary.service';
import { apibefore } from 'src/router';
import { ValidRSAInterceptor } from 'src/interceptor/validRSA';
import { ValidTokenInterceptor } from 'src/interceptor/validToken';
import { VideoLibrary } from './videoLibrary.entity';
import {
  secretId,
  secretKey,
  video_SubAppId_List,
  wx_appid,
  wx_appid_video_library,
} from '../../setting'
import { VideoEnum } from '../video/video.enum';
import { WXAPI } from 'src/common/wx_api';
import { TraceRelaTable } from '../traceRelaTable/traceRelaTable.entity';
import { WxUserService } from '../wxUser/wxUser.service';
import { WxUser } from '../wxUser/wxUser.entity';
import { MultiImgLibrary } from '../multiImgLibrary/multiImgLibrary.entity';
import utils from 'src/common/utils';
const tencentcloud = require("tencentcloud-sdk-nodejs");
const VodClient = tencentcloud.vod.v20180717.Client;
const clientConfig = {
  credential: {
    secretId: secretId,
    secretKey: secretKey,
  },
  region: "",
  profile: {
    httpProfile: {
      endpoint: "vod.tencentcloudapi.com",
    },
  },
};

@Controller(apibefore('/videoLibrary'))
@UseInterceptors(ValidRSAInterceptor)
@UseInterceptors(ValidTokenInterceptor)
export class VideoLibraryController {
  constructor(private readonly videoLibraryService: VideoLibraryService,
    private readonly wxUserServices: WxUserService
    ) {}

  @Get('findAll')
  findAll(@Request() req, @Query() params){
    let pageSize: number = parseInt(params.pageSize)
    let pageIndex: number = parseInt(params.pageIndex)
    let skip: number = pageSize * pageIndex

    return this.videoLibraryService.findAll(req.headers.wx_user, pageSize, skip)
  }
  
  /**
   * 修改视频封面图
   */
  uploadVideoCover(video_id: string, video_cover: string): Promise<string>{
    return new Promise((resolve,reject) => {
      const params = {
        FileId: video_id,
        CoverData: video_cover,
        SubAppId: video_SubAppId_List.videolibrary
      };
      const client = new VodClient(clientConfig);
      client.ModifyMediaInfo(params).then(
        (data) => {
          resolve(data.CoverUrl)
        },
        (err) => {
          resolve('')
        }
      );
    })
  }

  /**
   * 微信端删除视频
   * @param data 
   * @param req 
   * @returns 
   */
  @Post('/delete')
  @UseInterceptors(ValidTokenInterceptor)
  @UseInterceptors(ValidRSAInterceptor)
  async delete(@Body() data, @Request() req){
    let deleteYunRes = utils.deleteYunRes
    let err = await this.videoLibraryService.delete(data.video_id, req.headers.wx_user, deleteYunRes)
    if(err){
      return new HttpException(err, HttpStatus.INTERNAL_SERVER_ERROR)
    }else{
      return true
    }
  }

  @Post('client_upload_video')
  async client_upload_video(@Body() data: any, @Request() req) {
    let wx_user = req.headers.wx_user
    let traceRelaTableList:TraceRelaTable[] = []
    //上传视频封面
    if(data.type === VideoEnum.video){
      data.video_cover = await this.uploadVideoCover(data.video_id, data.video_cover)
    }else{
      const wxapi = new WXAPI()
      //查询用户信息
      let findUserInfo:WxUser = await this.wxUserServices.findOne_By_OpenId(wx_appid_video_library,wx_user)
      findUserInfo = findUserInfo[0]
      let wx_app_openid = findUserInfo.wx_app_openid
      //验证缩略图
      let result:any = await wxapi.mediaCheckAsync(data.video_cover, wx_app_openid)
      if(result?.trace_id){
        data.trace_id = result.trace_id
        //创建任务、表关联
        let addTrace = new TraceRelaTable()
        addTrace.trace_id = result.trace_id
        addTrace.table = 'video_library'
        addTrace.create_time = new Date()
        traceRelaTableList.push(addTrace)
      }else{
        return new HttpException('审核图片失败，请重新发布', HttpStatus.INTERNAL_SERVER_ERROR)
      }
      let mediaCheckError = false
      //验证多图
      if(data.multi_img?.length > 1){
        let valid_multi_img = () => {
          return new Promise((resolve,reject) => {
            let multi_img_list = data.multi_img.slice(1)
            let multi_img_len = multi_img_list.length
            multi_img_list.map(async (e:MultiImgLibrary) => {
              if(!mediaCheckError){
                let check_result:any = await wxapi.mediaCheckAsync(e.img, wx_app_openid)
                if(check_result?.trace_id){
                  e.trace_id = check_result.trace_id
                  //创建任务、表关联
                  let addTrace = new TraceRelaTable()
                  addTrace.trace_id = check_result.trace_id
                  addTrace.table = 'multi_img_library'
                  addTrace.create_time = new Date()
                  traceRelaTableList.push(addTrace)
                }else{
                  mediaCheckError = true
                }
              }
              multi_img_len--
              if(multi_img_len == 0){
                resolve(true)
              }
            })
          })
        }
        await valid_multi_img()
      }
      if(mediaCheckError){
        return new HttpException('审核图片失败，请重新发布', HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }
    let err = await this.videoLibraryService.Create(data, wx_user, data.multi_img, traceRelaTableList)
    if(err){
      return new HttpException(err, HttpStatus.INTERNAL_SERVER_ERROR)
    }else{
      return true
    }
  }
}
